package de.connecttext.dao.solr;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import de.connecttext.dao.DocumentIdGenerator;
import de.connecttext.model.MetaData;
import de.connecttext.model.TagVector;
import de.connecttext.model.TextDocument;
import de.connecttext.services.Stopwatch;
import de.connecttext.services.TagSelectAndRefiner;

public class WikipediaSolrDao extends SolrDao {

	private static WikipediaSolrDao instance;

	protected String fieldName = "text";
	Stopwatch stopwatch = new Stopwatch();

	public long elapsedTime1 = 0;
	public long elapsedTime2 = 0;
	public long elapsedTime3 = 0;

	@Override
	public TextDocument get(int row) {

		TextDocument toReturn = new TextDocument();
		toReturn.setUniqueDocId(DocumentIdGenerator.getInstance().generateId());
		// System.out.println("DocID in SolrDao: " + toReturn.getUniqueDocId());

		String solrId = null;

		List<TagVector> tagVectors = null;
		MetaData metaData = null;
		try {
			solrId = retrieveSolrId(row);
			tagVectors = retrieveTagVectors(solrId);
			metaData = retrieveMetaData(solrId);
		} catch (IOException e) {
			e.printStackTrace();
		}

		toReturn.setSolrId(solrId);
		toReturn.setMetaData(metaData);
		toReturn.setTagVectors(tagVectors);

		return toReturn;

	}

	private MetaData retrieveMetaData(String solrId) throws IOException {
		MetaData toReturn = new MetaData();

		String urlString = new String(
				"select?q=id:"
						+ solrId
						+ "&start=0&rows=1&fl=title,user&wt=json&hl=true&hl.fragsize=150");
		String responseString = urlRequest(urlString);
		// System.out.println(url);
		JSONObject root = (JSONObject) JSONValue.parse(responseString);
		JSONObject response = (JSONObject) root.get("response");
		JSONArray docs = (JSONArray) response.get("docs");
		JSONObject doc = (JSONObject) docs.get(0);
		String title = (String) doc.get("title");
		String author = (String) doc.get("user");

		toReturn.setTitle(title);
		toReturn.setAuthor(author);

		return toReturn;
	}

	public synchronized static WikipediaSolrDao getInstance() {
		if (instance == null)
			instance = new WikipediaSolrDao();
		return instance;
	}

}
